package com.yuwen.controller;

import com.yuwen.pojo.Article;
import com.yuwen.service.ArticleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class ArticleController {

    @Resource
    private ArticleService articleService;

    //显示markdown页面
    @GetMapping("/toEditor")
    public String toEditor(){
        return "editormd";
    }

    //上传图片并回显
    @ResponseBody
    @RequestMapping("/uploadImg")
    public Map<String,Object> uploadImg(HttpServletRequest request, @RequestParam(value = "editormd-image-file", required = false) MultipartFile file){
        Map<String,Object> map = new HashMap<>();
        if (file != null){
            //获取此项目的tomcat路径
            String webapp = request.getServletContext().getRealPath("/");
            try{
                //获取文件名
                String filename = file.getOriginalFilename();
                UUID uuid = UUID.randomUUID();
                String name = "";
                if (filename != null){
                    name = filename.substring(filename.lastIndexOf(".")); //获取文件后缀名
                }
                // 图片的路径+文件名称
                String fileName = "/upload/" + uuid + name;
                // 图片的在服务器上面的物理路径
                File destFile = new File(webapp, fileName);
                // 生成upload目录
                File parentFile = destFile.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();// 自动生成upload目录
                }
                // 把上传的临时图片，复制到当前项目的webapp路径
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(destFile));
                map.put("success",1); //设置回显的数据 0 表示上传失败，1 表示上传成功
                map.put("message","上传成功"); //提示的信息，上传成功或上传失败及错误信息等
                map.put("url",fileName); //图片回显的url 上传成功时才返回
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return map;
    }

    //添加文章信息
    @ResponseBody
    @PostMapping("/add")
    public Map<String,Object> add(String content,HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        boolean b = articleService.addArticle(content,request);
        if (b){
            map.put("msg","添加成功");
        }else{
            map.put("msg","添加失败");
        }
        return map;
    }

    //显示文章内容
    @GetMapping("/show")
    public String show(Model model){
        Article article = articleService.findById();
        model.addAttribute("article",article);
        return "show";
    }
}
